package xyz.xiaoshengfu.xrpc.common;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * <p>Title: LocalNetworkInformationUtil</p>
 * <p>Description: 获取本地网络信息工具类</p>
 * @author xiaoshengfu(2439323118@qq.com)
 * @date 2020年3月24日
 */
public class LocalNetworkInformationUtil {

	public static String getLocalIpv4Address() {
		Enumeration<NetworkInterface> allNetInterfaces = null;
		try {
			allNetInterfaces = NetworkInterface.getNetworkInterfaces();
		} catch (java.net.SocketException e) {
			e.printStackTrace();
		}
		InetAddress ip = null;
		while (allNetInterfaces.hasMoreElements()) {
			NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
			Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
			while (addresses.hasMoreElements()) {
				ip = (InetAddress) addresses.nextElement();
				if (ip != null && ip instanceof Inet4Address) {
					if (ip.getHostAddress().equals("127.0.0.1")) {
						continue;
					}
					return ip.getHostAddress();
				}
			}
		}
		return null;
	}
}
